package cn.edu.zafu.bigdata.bd121.studentdb.command.impl;

import cn.edu.zafu.bigdata.bd121.studentdb.cli.CliMain;
import cn.edu.zafu.bigdata.bd121.studentdb.command.BaseCommand;
import cn.edu.zafu.bigdata.bd121.studentdb.entity.StudentPO;
import cn.edu.zafu.bigdata.bd121.studentdb.utils.InputUtils;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Objects;

/**
 * 更新学生信息命令
 *
 * @author 202211090121
 */
public class UpdateStudent extends BaseCommand {

    /**
     * 处理用户输入
     */
    @Override
    protected void handleUserInput() {
        StudentPO studentPo = InputUtils.getStudentPo();
        if (Objects.isNull(studentPo)) {
            System.out.println("找不到该学生信息，请检查输入是否正确。");
        } else {
            System.out.println("找到该学生信息");
            System.out.println(studentPo);
            if (InputUtils.confirm()) {
                String name = InputUtils.getValidName();
                String phone = InputUtils.getValidPhone();
                try {
                    PreparedStatement statement = CliMain.connection.prepareStatement("UPDATE student121 SET name=?,phone=? WHERE id=?");
                    statement.setString(1, name);
                    statement.setString(2, phone);
                    statement.setLong(3, studentPo.getId());
                    statement.executeUpdate();
                    System.out.println("修改成功！");
                } catch (SQLException e) {
                    System.err.println("数据库异常");
                    throw new RuntimeException(e);
                }

            } else {
                System.out.println("修改操作已取消。");
            }
        }
    }
}
